﻿using UniRx;
using UnityEngine;

/// <summary>
/// 追击
/// </summary>
public class AIStateTrail : AIStateBase
{
    protected override string GetName() => "trail";

    private Timer.Simple m_Timer = new Timer.Simple();
    private float m_Axis;
    private EdgeChecker m_EdgeChecker;

    protected override void OnInit()
    {
        m_EdgeChecker = ai.entity.physics.edgeChecker;
        m_Timer.onFinish.Subscribe(_ => StartTimer()).AddTo(ai.entity);
    }

    protected override void OnEnter()
    {
        StartTimer();
    }

    protected override void OnExecute()
    {
        if (m_EdgeChecker.isEdge)
        {
            m_Timer.ShutDown();
            StartTimer();
        }
        ai.outputs.SetAxis("horizontalAxis", m_Axis);
    }

    protected override void OnExit()
    {
        if (m_Timer.isRuning)
        {
            m_Timer.ShutDown();
        }
    }

    private void StartTimer()
    {
        m_Axis = GetAxis();
        m_Timer.Start(UnitDefine.AI_STATE_FIXED_DURATION_MID);
    }

    private long GetAxis()
    {
        if (m_EdgeChecker.isEdge)
        {
            var dir = ai.entity.animator.direction.x;
            if (dir > 0) return -1;
            if (dir < 0) return 1;
        }
        var hatred = (ai.entity as MonsterEntity).hatred;
        if (hatred != null)
        {
            var dir = hatred.transform.position.x - ai.entity.transform.position.x;
            if (dir > 0) return 1;
            if (dir < 0) return -1;
        }
        return 0;
    }
}